package com.mx.zb.mng.ctrl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.mx.zb.mng.bo.*;
import com.mx.zb.mng.cache.IncCounter;
import com.mx.zb.mng.dao.*;
import com.mx.zb.mng.utils.*;
import com.mx.zb.mng.utils.context.ContextThread;
import com.mx.zb.mng.utils.db2.Page;
import com.mx.zb.mng.utils.db2.PageHelper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

@RestController
@RequestMapping("/a/biz")
public class TenantRestCtrl {
	
	@Autowired
	AgentMapper agentMapper;
	@Autowired
	TenantMapper tenantMapper;
	@Autowired
	OperatorMapper operatorMapper;
	
	@Autowired
	ModuleMapper moduleMapper;

	@Autowired
	TemplateMapper templateMapper;
	
	@Autowired
	RestInter    restInter;

	@Autowired
	IncCounter incCounter;


	@Value("${custom.tenant.newTenantPath}")
	private String tenantNewTenatPath;
	
	@Autowired  
    RestTemplate rest;
	
	@Value("${custom.tenant.host}")
	private String tenantHost;
	@Value("${custom.tenant.host1}")
	private String tenantHost04;
	@Value("${custom.tenant.isActivePath}")
	private String isActivePath;
	
	
	@Value("${custom.tenant.resetPwdPath}")
	private String resetPwdPath;
	
	@Value("${custom.tenant.EditTenantPath}")
	private String EditTenantPath;
	
	@Autowired
	BizIndustryMapper bizIndustryMapper;
	
	Logger log = LoggerFactory.getLogger(this.getClass());
	
	@SuppressWarnings({ "unused" })
	@RequestMapping(value = { "/tenant/tenant" },method= {RequestMethod.PUT})
	@Transactional
	public AjaxResult addTenant(@RequestBody JSONObject params) {
		Tenant t=params.getObject("tenant",Tenant.class);
		Operator operator =params.getObject("operator",Operator.class);
		String tenantId = UnionCode.getShortUuid();
		String agentId = ContextThread.get().getAgentId();
		String operatorId =  ContextThread.get().getOperatorId();
		Agent agentPojo = agentMapper.selectByPrimaryKey(agentId);

		String moduleId = UnionCode.getShortUuid();
		String roleId = UnionCode.getShortUuid();
		Integer gcode = incCounter.getMaxAgentCode();
		String templateId=t.getTemplateId();
		if("零售电商".equals(templateId)) {
			t.setTemplate("云商(秒到2.0)");
		}else if("技师服务".equals(templateId)) {
			t.setTemplate("秒到来店");
		}
		
		t.setIsActive("1");
		t.setId(tenantId);
		t.setLevelCode(agentPojo.getLevelCode());
		t.setAgentId(agentId);
		t.setCreateDate(new Date());
		t.setCreateOper(operatorId);
		t.setCode(gcode.toString());// 代理商编码
		
		Calendar car = Calendar.getInstance();
		car.setTime(new Date());
		car.add(Calendar.YEAR, 1);//加一年
		Date userStopDate = car.getTime();
		t.setStopUseDate(userStopDate);
	
		operator.setId(UnionCode.getShortUuid());
		operator.setCreateDate(new Date());
		operator.setCreateOper(ContextThread.get().getOperatorId());
		operator.setUpdateOper(ContextThread.get().getOperatorId());
		operator.setAgentId(agentId);
		operator.setLoginName(operator.getPhone());
		operator.setTenantCode(Long.parseLong(gcode.toString()));
		String enPass = Crypt.enAes(operator.getPhone());
		operator.setPassword(enPass);
		operator.setRoleId(roleId);
		Role r = new Role();
		r.setAgentId(agentId);
		r.setName("管理员");
		r.setId(roleId);
		r.setCreateDate(new Date());
		r.setCreateOper(ContextThread.get().getOperatorId());
		r.setUpdateDate(new Date());
		r.setUpdateOper(ContextThread.get().getOperatorId());
		// roleMapper.insert(r);

		int[] num = new int[1];
		num[0] = 1;
		List<Module> list = moduleMapper.selectByRoleSet(num);
		if (list != null && list.size() > 0) {
			for (Module module : list) {
				RoleModuleRela pojo = new RoleModuleRela();
				pojo.setRoleId(roleId);
				pojo.setModuleId(module.getId());
				pojo.setAgentId(agentId);
				// roleModuleRelaMapper.insert(pojo);
			}
		}

		JSONObject postData = new JSONObject();
		t.setCreateOper(agentId); // 创建该用户的代理商
		postData.put("tenant", t);
		postData.put("operater", operator);
		String host=tenantHost;
		if("技师服务".equals(t.getTemplateId())) {
			host=tenantHost04;
		}
		JSONObject json  = restInter.postJson(host + tenantNewTenatPath, postData);
		if(json.size()<1) {
			return new AjaxResult().failure("后台异常请联系管理员!");
		}
		if (!"1".equals(json.getString("status"))) {
			return new AjaxResult().failure("保存失败!");
		}
		t.setCreateOper(operatorId);
		tenantMapper.insert(t);

		// 修改代理商的套数
		Agent agentEdit = agentMapper.selectByPrimaryKey(ContextThread.get().getAgentId());
		if (agentEdit != null) {
			//if (agentEdit.getLevelCode().length() > 4) {
				if(!Constant.headquarters.equals(agentEdit.getType())){
				agentEdit.setLeftCount(agentEdit.getLeftCount() - 1);// 剩余套数
				agentMapper.updateByPrimaryKeySelective(agentEdit);
			} else {
				// 总部不用减
			}
		}
		
		/*	model.addAttribute("tenant", t);
		// Operator op = operatorMapper.selectByPrimaryKey(t.getCreateOper());
		Agent a = agentMapper.selectByPrimaryKey(t.getAgentId());
		model.addAttribute("OperatorName", a.getName());
		List<Template> templist = templateMapper.findAll();
		model.addAttribute("templates", templist);*/
		return new AjaxResult().success();
	}
	
	@RequestMapping(value = { "/tenant/tenant" },method= {RequestMethod.POST})
	@Transactional
	public AjaxResult  edittenant(@RequestBody JSONObject params) {
		Tenant o=params.getObject("tenant",Tenant.class);
		o.setUpdateDate(o.getCreateDate());
		o.setUpdateOper(ContextThread.get().getOperatorId());

		JSONObject postData = new JSONObject();
		postData.put("tenant", o);
		String host=tenantHost;
		if("技师服务".equals(o.getTemplateId())) {
			host=tenantHost04;
		}
		JSONObject json  = restInter.postJson(host + EditTenantPath, postData);
		if(json.size()<1) {
			return new AjaxResult().failure("后台异常请联系管理员!");
		}
		if (!"1".equals(json.getString("status"))) {
			return new AjaxResult().failure("修改失败!");
		}
		tenantMapper.updateByPrimaryKeySelective(o);
		/*Tenant ta = tenantMapper.selectByPrimaryKey(o.getId());
		model.addAttribute("tenant", ta);
		// Operator op = operatorMapper.selectByPrimaryKey(ta.getCreateOper());
		Agent a = agentMapper.selectByPrimaryKey(ta.getAgentId());
		model.addAttribute("OperatorName", a.getName());
		List<Template> templist = templateMapper.findAll();
		model.addAttribute("templates", templist);*/
		return new AjaxResult().success();
	}
	
	@RequestMapping(value= {"/tenant/tocheck"},method= {RequestMethod.POST})
	@ResponseBody
	public AjaxResult toTenantCheck( Agent a,Model model) {
		if(a.getName()=="" ) {
			a.setName(null);
		}
		if(a.getPhone()=="" ) {
			a.setPhone(null);
		}
		List<Agent> agentList = agentMapper.queryPage(a);
			model.addAttribute("tpList", agentList);
		return new AjaxResult().success(agentList);
	}
	
	@RequestMapping(value= {"/tenants"}, method= {RequestMethod.GET})
	public AjaxResult getList() {
		Tenant o = new Tenant();
		Page<Tenant> pages = new Page<Tenant>();
		String search = ContextThread.get().getSearch();
		 SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd HH:mm");  
		if (search == null || search == "") { // 表示首次加载
			/*o.setAgentId(ContextThread.get().getAgentId());
			 pages = tenantMapper.queryPage(o);*/
		}else {
			o = JSON.parseObject(search, Tenant.class);
			 try {
				 if(o.getCreateDate1()!= null &&!"".equals(o.getCreateDate1().toString())) {
					 o.setCreateDate(sdf.parse(o.getCreateDate1().toString()));
				 }
				 if(o.getCreateDate2()!= null &&!"".equals( o.getCreateDate2().toString())) {
						o.setUpdateDate(sdf.parse(o.getCreateDate2().toString()));
				 }
			} catch (ParseException e) {
			e.printStackTrace();
			}  
		}
		String agentId=ContextThread.get().getAgentId();
		Agent agent =agentMapper.selectByPrimaryKey(agentId);
		if(!Constant.headquarters.equals(agent.getType())) {
			o.setAgentId(agentId);
		}
		PageHelper.startPage();
		pages =	tenantMapper.selectByParams(o);
		//将上级姓名暂时存在updateOper中以供页面显示
		if(pages!=null) {
			for (Tenant p :pages) {
				String agentId1=p.getAgentId();
				p.setUpdateOper("");
				if(StringUtils.hasText(agentId1)) {
					Agent pojo =agentMapper.selectByPrimaryKey(agentId1);
					if(pojo!=null) {
						p.setUpdateOper(pojo.getName());
					}
				}
			}
		}
		return new AjaxResult().success(pages);
	}
	
	
	@RequestMapping(value = { "/isAdd" }, method = { RequestMethod.GET })
	public AjaxResult isAdd() {
		// 代理商添加商户之前查询套数看够不够添加
		Agent agentget = agentMapper.selectByPrimaryKey(ContextThread.get().getAgentId());
		if (agentget != null) {
			if (  !Constant.headquarters.equals(agentget.getType())) { // 代理商
				if (agentget.getLeftCount() < 1) {
					// 不能添加商户
				      return new AjaxResult().failure("套数不够不能添加商户！");
				}
			}
		}
		   return new AjaxResult().success();

	}
	
	@RequestMapping(value= {"/tenant"}, method= {RequestMethod.DELETE})
	@Transactional
	public AjaxResult delete(@RequestBody Tenant o) {	
		
		Tenant pojo=tenantMapper.selectByPrimaryKey(o.getId());
		String active=pojo.getIsActive();
		if("0".equals(active)) {
			o.setIsActive("1");
		}else {
			o.setIsActive("0");
		}
	
		JSONObject postData = new JSONObject();  
    	
        postData.put("tenant", o);
    	String host=tenantHost;
		if("技师服务".equals(pojo.getTemplateId())) {
			host=tenantHost04;
		}
		JSONObject json  = restInter.postJson(host + isActivePath, postData);
		if(json.size()<1) {
			return new AjaxResult().failure("后台异常请联系管理员!");
		}
		if (!"1".equals(json.getString("status"))) {
			return new AjaxResult().failure("修改失败!");
		}
     
    	tenantMapper.updateByPrimaryKeySelective(o);
		return new AjaxResult().success();
	}

	/**
	 * 续费 如果禁用的或者过期的，则要重新开通云商或者来店
	 * @param o
	 * @return
	 */
	@RequestMapping(value= {"/tenant/xf"}, method= {RequestMethod.POST})
	@Transactional
	public AjaxResult xf(@RequestBody Tenant o) {
		Tenant pojo=tenantMapper.selectByPrimaryKey(o.getId());
		String agentId=ContextThread.get().getAgentId();
		Agent agent1=agentMapper.selectByPrimaryKey(agentId);
		Agent agent=agentMapper.selectByPrimaryKey(pojo.getAgentId());
		if(agent!=null&&agent1!=null&&!"总部".equals(agent1.getType())){
          Long leftCount=agent.getLeftCount();
          if(leftCount<=0){
			  return new AjaxResult().failure("套数不足，无法续费");
		  }
			agent.setLeftCount(leftCount-1);
		}
		String active=pojo.getIsActive();
		Calendar car = Calendar.getInstance();
		if(new Date().before(pojo.getStopUseDate())){
			car.setTime(pojo.getStopUseDate());
		}else{
			car.setTime(new Date());
		}
		car.add(Calendar.YEAR, 1);//加一年
		pojo.setStopUseDate(car.getTime());
		o.setStopUseDate(car.getTime());
		if(!"1".equals(active)||1==1) {
			o.setIsActive("1");
			JSONObject postData = new JSONObject();
			postData.put("tenant", o);
			String host=tenantHost;
			if("技师服务".equals(pojo.getTemplateId())) {
				host=tenantHost04;
			}
			JSONObject json  = restInter.postJson(host + isActivePath, postData);
			if(json.size()<1) {
				return new AjaxResult().failure("后台异常请联系管理员!");
			}
			if (!"1".equals(json.getString("status"))) {
				return new AjaxResult().failure("修改失败!");
			}
		}
		pojo.setIsActive("1");
		tenantMapper.updateByPrimaryKeySelective(pojo);
		agentMapper.updateByPrimaryKeySelective(agent);
		return new AjaxResult().success();
	}



	@RequestMapping(value = { "/tenant/resetPwd" },method= {RequestMethod.PUT})
	@ResponseBody
	public AjaxResult resetPwd(@RequestBody JSONObject jsonObject) {
		   //设置header
		String id= jsonObject.getString("id");
		Tenant o=tenantMapper.selectByPrimaryKey(id);
	      JSONObject postData = new JSONObject();  
        postData.put("tid", id);
    	String host=tenantHost;
    	if("技师服务".equals(o.getTemplateId())) {
			host=tenantHost04;
		}
    	log.error("t.getTemplateId()============重置商户密码======================="+o.getTemplateId());
		log.error("host==============================="+host);
    	JSONObject json  = restInter.postJson(host + resetPwdPath, postData);
		if(json.size()<1) {
			return new AjaxResult().failure("后台异常请联系管理员!");
		}
		if (!"1".equals(json.getString("status"))) {
			return new AjaxResult().failure("修改失败!");
		}
		return new AjaxResult().success();
	}
	
	
	@RequestMapping(value= {"/tenant/getOper"}, method= {RequestMethod.POST})
	@Transactional
	@ResponseBody
	public AjaxResult getCreateOper(@RequestBody JSONObject param) {
		String createId = "";
		if(param!=null) {
			 createId = param.get("id").toString();
		}
	Operator op = operatorMapper.selectByPrimaryKey(createId);	
	Agent a=new Agent();
	if(op!=null) {
		 a = agentMapper.selectByPrimaryKey(op.getAgentId());	

	}
		return new AjaxResult().success(a);		
	}
	
	@RequestMapping(value= {"/tenant/openTenant"}, method= {RequestMethod.POST})
	@Transactional
	@ResponseBody
	//重新开始商户
	public AjaxResult openTenant(@RequestBody JSONObject param) {
		String tenantId = "";
		if(param!=null) {
			tenantId = param.get("id").toString();
		}
		Tenant o=tenantMapper.selectByPrimaryKey(tenantId);
		Tenant t = new Tenant();
		t.setId(tenantId);
		t.setIsActive("1");//开启
		Calendar car = Calendar.getInstance();
		car.setTime(new Date());
		car.add(Calendar.YEAR, 1);//加一年
		Date userStopDate = car.getTime();
		t.setStopUseDate(userStopDate);
		/*同时要减去上级的代理套数==================================*/

		Agent agent=agentMapper.selectByPrimaryKey(o.getAgentId());
		if(agent!=null&&!"总部".equals(agent.getType())){
			Long leftCount=agent.getLeftCount();
			if(leftCount<=0){
				return new AjaxResult().failure("套数不足，无法启用");
			}
			agent.setLeftCount(leftCount-1);
		}
		
		// 更新商户平台的商户信息
		JSONObject postData = new JSONObject();
		postData.put("tenant", t);
		String host=tenantHost;
		if("技师服务".equals(o.getTemplateId())) {
			host=tenantHost04;
		}
		JSONObject json  = restInter.postJson(host + EditTenantPath, postData);
		if(json.size()<1) {
			return new AjaxResult().failure("后台异常请联系管理员!");
		}
		if (!"1".equals(json.getString("status"))) {
			return new AjaxResult().failure("修改失败!");
		}
		tenantMapper.updateByPrimaryKeySelective(t);
		agentMapper.updateByPrimaryKeySelective(agent);
		return new AjaxResult().success();		
	}
	
	
	
	@RequestMapping(value= {"/getTenants"}, method= {RequestMethod.GET})
	public AjaxResult getTenants(Tenant o) {
		PageHelper.startPage();
		Page<Tenant> pages =	tenantMapper.selectByParams(o);
		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
		StringToDateConverter converter=new StringToDateConverter("yyyy-MM-dd");

		if(pages!=null) 
		{
			for(Tenant tenant:pages) {
				Date stopUseDate=tenant.getStopUseDate();
				if(stopUseDate==null) {
					stopUseDate=new Date();
				}
				Date beginDate=converter.convert(format.format(tenant.getCreateDate()));//开始时间
				Date endDate=converter.convert(format.format(stopUseDate));//结束时间
				 int cnt = DateUtil.longOfTwoDate(beginDate, endDate);
				 tenant.setNums(new Long(cnt));
			}
		}
		return new AjaxResult().success(pages);
	}
	
	//代理商转移
	@RequestMapping(value= {"/updateZyTennat"}, method= {RequestMethod.POST})
	public AjaxResult updateZyTennat(@RequestBody Tenant o) {
		o.setUpdateDate(new Date());
		o.setUpdateOper(ContextThread.get().getOperatorId());
		tenantMapper.updateByPrimaryKeySelective(o);
		return new AjaxResult().success();
	}
	
	
	//模板变了之后对应的类目变动
	@RequestMapping(value= {"/getCategory"}, method= {RequestMethod.POST})
	public AjaxResult getCategory(@RequestBody BizIndustry o) {
		List<BizIndustry> list=bizIndustryMapper.queryList(o);
		return new AjaxResult().success(list);
	}
	
	
	}